/**
 * Created by linmc on 2015/10/3.
 * 用户登录时，创建ȡaccess_token
 */
'use strict';
var jwt = require('jsonwebtoken');
var User = require('../model/user');

module.exports = {
    gettoken: function *() {
        var username = this.request.query.username;
        var password = this.request.query.password;
        try {
            yield User.findAll({
                    where: {
                        FName: username
                    }}
                ).then((users)=>{
                if(users&&users.length>0){
                if(users[0].FPassword != password){
                    this.body = JSON.stringify({success: false, message: '认证失败，密码错误'});
                }else{
                    // 创建token
                    var token = jwt.sign(users[0], 'supersecret', {
                        expiresInMinutes: 1440 // 设置有效时间
                 });
                    this.body = JSON.stringify({success: false, message: '认证成功，生成token成功ȷ',token: token});
             }
            }else{
                this.body = JSON.stringify({success: false, message: '认证失败，找不到用户名'});
        }
        });

        } catch (error) {
         this.status = 500;
        this.body = {status: 'failed', error: error};
    }
        }

};